package com.sm.imlibrary.event;

import com.sm.imlibrary.imsdk.SIMManager;
import com.sm.imlibrary.imsdk.SIMMessage;
import com.sm.imlibrary.imsdk.SIMMessageListener;

import java.util.List;
import java.util.Observable;

/**
 * created by zhud on 2019/7/9
 * 消息通知事件，上层界面可以订阅此事件
 */
public class MessageEvent extends Observable implements SIMMessageListener {
    private static MessageEvent instance;

    private MessageEvent() {
        //注册消息监听器
        SIMManager.getInstance().addMessageListener(this);
    }

    public static MessageEvent getInstance() {
        if (instance == null) {
            synchronized (MessageEvent.class) {
                if (instance == null) {
                    instance = new MessageEvent();
                }
            }
        }
        return instance;
    }

    @Override
    public boolean onNewMessages(List<SIMMessage> list) {
        for (SIMMessage item : list) {
            setChanged();
            notifyObservers(item);
        }
        return false;
    }

    /**
     * 主动通知新消息
     */
    public void onNewMessage(SIMMessage message) {
        setChanged();
        notifyObservers(message);

    }

    /**
     * 清理消息监听
     */
    public void clear() {
        instance = null;
        SIMManager.getInstance().removeMessageListener(this);
    }

}
